package com.lanou3g.ptp.api.web.controller;

import com.lanou3g.ptp.utils.FileNameUtils;
import com.lanou3g.ptp.utils.PtpResult;
import com.lanou3g.ptp.utils.PtpResultUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Api(description = "资源接口")
@Controller
@RequestMapping("/resource")
public class ResourceController {

    @Value("${ptp.resource.remote.host}")
    private String remoteHost;
    @Value("${ptp.resource.remote.port}")
    private String remotePort;
    @Value("${ptp.resource.remote.dir.images}")
    private String remoteImageDir;

    @ResponseBody
    @PostMapping("/image")
    public PtpResult uploadImage(MultipartFile image) {
        String fileName = FileNameUtils.generateFileName(MimeTypeUtils.IMAGE_JPEG_VALUE);

        String path = getPath("http", remoteHost, remotePort, remoteImageDir, fileName);
        try {
            Client client = Client.create();
            WebResource resource = client.resource(path);
            resource.put(image.getInputStream());
            return PtpResultUtils.ok(path);
        } catch (Exception e) {
            return PtpResultUtils.error(500, "文件上传失败");
        }

    }

    private String getPath(String protocol, String host, String port, String dir, String fileName) {
        StringBuilder sb = new StringBuilder();
        sb.append(protocol);
        sb.append("://");
        sb.append(host);
        sb.append(":");
        sb.append(port);
        if (!dir.startsWith("/")) {
            sb.append("/");
        }
        sb.append(dir);
        if (!dir.endsWith("/") && !fileName.startsWith("/")) {
            sb.append("/");
        }
        sb.append(fileName);
        return sb.toString();
    }

}
